//导入Vue
import Vue from 'vue'
//导入VueRouter
import VueRouter from 'vue-router'
//导入路由配置文件
import routes from '@/router/config'
import {getStore} from '@/util/h5store'
import {TOKEN_KEY} from '@/util/constant'
//导入nprogress依赖包
import NProgress from 'nprogress'
//将nprogress的css导入
import 'nprogress/nprogress.css'
NProgress.configure({
   easing: "ease-in-out",
   speed: 300,
   trickeSpeed: 300,
})
//
//注册VueRouter
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalReplace.call(this, location, onResolve, onReject);
    return originalReplace.call(this, location).catch(err => err);
};
/*
  创建router实例
  构造函数的参数是一个配置对象,
  配置对象中常见的选项
  1、routes:路由规则表
  2、mode:常见的有两种模式
    hash:hash模式，不美观，在微前端项目中使用不了
    history:history模式：打包上线之后回出现404，但在脚手架环境下不会出现404
  3、bash：基础路径：打包上线的时候使用
  4、scrollBehavior：滚动
*/
const router=new VueRouter({
    routes,
    mode:'hash'
})
//定义一个变量
let menus=null
//设置路由全局前置守卫:当进入目标路由之前会调用该函数
router.beforeEach(async(to,from,next)=>{
  //启动动画
 
  NProgress.start()
  if(to.path=="/login"){
    next()
  }else{
    if(getStore(TOKEN_KEY)){
      if(!menus){
        try{
          const result=await Vue.prototype.$api.users.getUserInfo()
          //定义一个变量用来接收后端的所有路由规则
          let permissionList=result.data.permissionList
          //将查出来的数据赋值到menus
          menus=permissionList
          //给homeName这个路由对象上添加一个子路由
          router.addRoute("homeName",{
            path:'userModify',
            component:()=>import(`@/views/users/userModify.vue`)
          })
          console.log('permissionList',permissionList);
          //使用for循环进行遍历
          for(let i=0;i<permissionList.length;i++){
            let routeObj=permissionList[i]
            //addRoute(参数1,参数2):用来动态添加一条新的路由规则，参数1：父路由的name,参数2：路由对象
           
            router.addRoute("homeName",{
              path:routeObj.path,
              component:()=>import(`@/views${routeObj.permission}.vue`),
              meta:{
                name:routeObj.title
              }
            })
          }
          //查看所有路由
          console.log('routes',router.getRoutes());
          next({path:to.path})
        }catch(err){
           next('/login')
        }
      }
      next()//进入到目标地
    }else{
      Vue.prototype.$message.warning("您还没有登录请先登录")
      next("/login")
    }
  }
})
//路由后置守卫
router.afterEach((to,from)=>{
  NProgress.done()
})
//默认导出
export default router
